var acdProtocolIdx = -1;
function openAcdProtocol() {
  var isProtocolCheck = sessionStorage.getItem("acd_isProtocolCheck");
  if (isProtocolCheck)
    return;
  acdProtocolIdx = layer.open({
    type: 2,
    title: false,
    closeBtn: 0, //不显示关闭按钮
    shade: [0.7],
    area: ['800px', '360px'],
    maxmin: false, //开启最大化最小化按钮
    anim: 2,
    content: ['https://apphg.singlewindow.cn/acd/acd/pages/pageframe/selectProtocol.jsp?functionId=2'],
    end: function() {

    }
  });
}


function menuItem() {
  // 获取标识数据
  var dataUrl = $(this).attr('href'),
    dataIndex = $(this).data('index'),
    menuName = $.trim($(this).text()),
    flag = true;
  if (dataUrl == undefined || $.trim(dataUrl).length == 0)return false;
  // 选项卡菜单已存在
  if ( top.$('.J_menuTab')){
    top.$('.J_menuTab').each(function () {
      if ($(this).data('id') == dataUrl) {
        if (!$(this).hasClass('active')) {
          $(this).addClass('active').siblings('.J_menuTab').removeClass('active');
          scrollToTab(this);
          // 显示tab对应的内容区
          top.$('.J_mainContent .J_iframe').each(function () {
            if ($(this).data('id') == dataUrl) {
              $(this).show().siblings('.J_iframe').hide();
              //谷歌兼容性
              var iframe = top.document.getElementsByName(this.name)[0];
              iframe.style.height = '99%';
              iframe.scrollWidth;
              iframe.style.height = '100%';
              return false;
            }
          });
        }
        flag = false;
        return false;
      }
    });
  }

  // 选项卡菜单不存在
  if (flag) {
    var str = '<a href="javascript:;" class="active J_menuTab" data-id="' + dataUrl + '">' + menuName + ' <i class="fa fa-times-circle"></i></a>';
    top.$('.J_menuTab').removeClass('active');

    // 添加选项卡对应的iframe
    var str1 = '<iframe class="J_iframe" name="iframe' + dataIndex + '" width="100%" height="100%" src="' + dataUrl + '" frameborder="0" data-id="' + dataUrl + '" seamless></iframe>';
    top.$('.J_mainContent').find('iframe.J_iframe').hide().parents('.J_mainContent').append(str1);

    //显示loading提示
//        var loading = layer.load();
//
//        $('.J_mainContent iframe:visible').load(function () {
//            //iframe加载完成后隐藏loading提示
//            layer.close(loading);
//        });
    // 添加选项卡
    top.$('.J_menuTabs .page-tabs-content').append(str);
    scrollToTab(top.$('.J_menuTab.active'));
  }
  return false;
}

//计算元素集合的总宽度
function calSumWidth(elements) {
  var width = 0;
  var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  if (userAgent.indexOf("Firefox") > -1) {
    for(var i=0;i<$(elements).length;i++){
      width +=elements[i].offsetWidth;
    }
  } else{
    $(elements).each(function () {
      width += $(this).outerWidth(true);
    });
  }
  return width;
}

//滚动到指定选项卡
function scrollToTab(element) {
  var marginLeftVal = calSumWidth($(element).prevAll()), marginRightVal = calSumWidth($(element).nextAll());
  // 可视区域非tab宽度
  var tabOuterWidth = calSumWidth(top.$(".content-tabs").children().not(".J_menuTabs"));
  //可视区域tab宽度
  var visibleWidth = top.$(".content-tabs").outerWidth(true) - tabOuterWidth;
  //实际滚动宽度
  var scrollVal = 0;
  var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  if (userAgent.indexOf("Firefox") > -1) {
    var elementNext=$(element).next().get(0);
    var elementPrev=$(element).prev().get(0);
    var elementThis=$(element).get(0);
    var elementPrev_W=0;
    var elementNext_W=0;
    if(elementNext){
      elementNext_W=elementNext.offsetWidth;
    }
    if(elementPrev){
      elementPrev_W=elementPrev.offsetWidth
    }

    if (top.$(".page-tabs-content").outerWidth() < visibleWidth) {
      scrollVal = 0;
    } else if (marginRightVal <= (visibleWidth - elementThis.offsetWidth - elementNext_W)) {
      if ((visibleWidth - elementNext_W) > marginRightVal) {
        scrollVal = marginLeftVal;
        var tabElement = element;
        while ((scrollVal - elementThis.offsetWidth) > (top.$(".page-tabs-content").outerWidth() - visibleWidth)) {
          scrollVal -= elementPrev_W;
          tabElement = $(element).prev();
        }
      }
    } else if (marginLeftVal > (visibleWidth - elementThis.offsetWidth - elementPrev_W)) {
      scrollVal = marginLeftVal - elementPrev_W;
    }
  }else{
    if (top.$(".page-tabs-content").outerWidth() < visibleWidth) {
      scrollVal = 0;
    } else if (marginRightVal <= (visibleWidth - $(element).outerWidth(true) - $(element).next().outerWidth(true))) {
      if ((visibleWidth - $(element).next().outerWidth(true)) > marginRightVal) {
        scrollVal = marginLeftVal;
        var tabElement = element;
        while ((scrollVal - $(tabElement).outerWidth()) > (top.$(".page-tabs-content").outerWidth() - visibleWidth)) {
          scrollVal -= $(tabElement).prev().outerWidth();
          tabElement = $(tabElement).prev();
        }
      }
    } else if (marginLeftVal > (visibleWidth - $(element).outerWidth(true) - $(element).prev().outerWidth(true))) {
      scrollVal = marginLeftVal - $(element).prev().outerWidth(true);
    }
  }
  //添加滚动动画
  top.$('.page-tabs-content').animate({
    marginLeft: 0 - scrollVal + 'px'
  }, "fast");
}

//滚动到已激活的选项卡
function showActiveTab(){
  scrollToTab(top.$('.J_menuTab.active'));
}
/**
 * 描述：打开新的框架tab页并传参
 **/
function openTab(menuName, menuNameCN, url, tabParamJson) {
  var paramStr = JSON.stringify(tabParamJson);
  if (top.$(".J_menuItem").length > 0) {
    if (top.$('a#' + menuName).length > 0) {
      top.$('a#' + menuName).remove();
      refreshTabByMenuSW(menuNameCN);
    }
    var dataIndex = top.$(".J_menuItem").length;
    var hrefEle = '<a id ="' + menuName + '" title="' + menuNameCN
      + '" class="J_menuItem" href="' + url + '" data-index="'
      + dataIndex + '" style="display:none;" data=' + paramStr + '>' + menuNameCN
      + '</a>';
    top.$('body').append(hrefEle);
    top.$('.J_menuItem').on('click', menuItem);
    top.$('.J_tabShowActive').on('click', showActiveTab);
    top.$('a#' + menuName)[0].click();
  } else {
    window.location.href = url;
  }
}

//刷新框架tab页
function refreshTabByMenuSW(menuNameCN) {
  var refreshTabId;
  top.$('.J_menuTab').each(function() {
    if ($(this)[0].innerText.replace(/(^\s*)|(\s*$)/g, '') == menuNameCN) {
      refreshTabId = $(this).data('id');
      $(this).click();
      return false;
    }
  });
  top.$('.J_mainContent .J_iframe').each(function() {
    if ($(this).data('id') == refreshTabId) {
      $(this).attr('src', $(this).attr('src'));
      return false;
    }
  });
}


var loadingIndex = -1;
function initIndexMenu(params) {
  var menuId = params.menuId;
  if (menuId == "noc") {
    loadingIndex = layer.load(1, {
      shade: [0.1, '#fff']
      // 0.1透明度的白色背景
    });
    var src = "https://apphg.singlewindow.cn/noc/getCookie.c?functionId=2";
    window.open(src,'noc_selectHGCode',"height=0,width=0");
    setTimeout(function() {
      var src = "https://apphg.singlewindow.cn/noc/selectHGCode.c?functionId=2&data=" + params.cusRegNo;
      var tabFrame = document.getElementById("indexFrame");
      var iframe = document.createElement("iframe");
      iframe.src = src;
      iframe.style = "display:none";
      document.body.appendChild(iframe);
      tabFrame.src = params.homePageUrl;

      if (tabFrame.attachEvent) {
        tabFrame.attachEvent("onload", function() {
          layer.close(loadingIndex);
        });
      } else {
        tabFrame.onload = function() {
          layer.close(loadingIndex);
        };
      }
    },300);
  } else if (menuId == "acd") {
    // loadingIndex = layer.load(1, {
    //   shade: [0.4, '#fff']
    //   // 0.1透明度的白色背景
    // });
    // var iframe = document.createElement("iframe");
    var src = "https://apphg.singlewindow.cn/acd/acdPageFrameAction/putRegCoCgac.action?functionId=2&data=" + params.cusRegNo;
    var win = window.open(src,'acd_putRegCoCgac',"height=0,width=0");
    setTimeout(function() {
      openAcdProtocol();
    },300);
    // iframe.src = src;
    // iframe.style = "display:none";
    // document.body.appendChild(iframe);

    // if (iframe.attachEvent) {
    //   iframe.attachEvent("onload", function() {
    //     layer.close(loadingIndex);
    //     // openAcdProtocol();
    //   });
    // } else {
    //   iframe.onload = function() {
    //     layer.close(loadingIndex);
    //     openAcdProtocol();
    //   };
    // }

  }
}

$(function() {

  window.addEventListener('message', function(e) {
    //data: {type:'acd_selectProtocol',code:'ok',data:{}}
    var data = e.data;
    if (data.type === 'acd_selectProtocol') {
      sessionStorage.setItem("acd_isProtocolCheck", true);
      if (acdProtocolIdx >= 0) {
        layer.close(acdProtocolIdx);
        acdProtocolIdx = -1;
      }
    } else if (data.type === 'acd_initPage') {
      if (loadingIndex != -1) {
        layer.close(loadingIndex);
        loadingIndex = -1;
      }
      openAcdProtocol();
    } else if (data.type === 'base_tabopen') {
      openTab(data.data.menuName, data.data.menuNameCN, data.data.url)
    }

  }, false);
})

